<?php

namespace MoChat\Salesman\Action;

use Hyperf\DbConnection\Db;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 首页数据展示
 * @Controller
 */
class TaskData extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/salesman/home", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $startTime = "2021-06-01 00:00:00";
        $endTime = date('Y-m-d H:i:s');
        if (!empty($data['time_enum']) && is_numeric($data['time_enum'])) {
            switch ($data['time_enum']) {
                //年
                case 1:
                    $startTime = date('Y-01-01 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                //月
                case 2:
                    $startTime = date('Y-m-01 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                //日
                case 3:
                    $startTime = date('Y-m-d 00:00:00');
                    $endTime = date('Y-m-d H:i:s');
                    break;
                //周
                case 4:
                    $week = date("w");
                    $week = $week ? $week - 1 : 6;
                    $startTime = date('Y-m-d 00:00:00', strtotime('-' . $week . ' day'));
                    $endTime = date('Y-m-d H:i:s');
                    break;
                default:
            }
        }
        $workEmployeeId = $user['workEmployeeId'];

        $uniqueIds = Db::table('client')->where('work_employee_id', $workEmployeeId)->pluck('unique_id');
        $uniqueIds = empty($uniqueIds) ? [] : $uniqueIds->toArray();
        //客户数
        $userCount = Db::connection('b2b')->table('user as user')
            ->whereIn('user.unique_id', $uniqueIds)
            ->count();
        //下单客户数
        $userOrderCount = Db::connection('b2b')->table('user_order as order')
            ->join('user as user', 'user.id', '=', 'order.USER_ID')
            ->whereIn('user.unique_id', $uniqueIds)
            ->where('order.CREATE_TIME', '>=', $startTime)
            ->where('order.CREATE_TIME', '<', $endTime)
            ->groupBy(['user.id'])->count();
        //未下单客户
        $noUserOrderCount = $userCount ? bcsub($userCount, $userOrderCount, 0) : 0;
        //TODO  首页统计
        return [
            'numberCheckIns' => Db::table('clock_record')
                ->where('work_employee_id', $workEmployeeId)
                ->where('created_at', '>=', $startTime)
                ->where('created_at', '<', $endTime)
                ->count(),//签到次数
            'numberVisits' => 0,//进店次数
            'placeOrderRate' => $userCount ? bcmul(bcdiv($userOrderCount, $userCount, 6), 100, 2) . '%' : '0%',//下单率
            'placeOrderMember' => $userOrderCount,//下单客户数
            'notPlaceOrderMember' => $noUserOrderCount,//未下单客户
            'yesLogged' => 0,//已登录客户
            'notLogged' => 0,//未登录客户数
        ];
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'time_enum' => 'in:1,2,3,4',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'time_enum.in' => 'time_enum参数错误',
        ];
    }
}
